/**
 * 个性化推荐算法服务
 * 实现用户行为分析、内容标签和用户画像功能
 */

import apiClient from '@/utils/request';

// 用户行为数据接口
export interface UserBehavior {
  user_id: string;
  action_type: 'view' | 'like' | 'share' | 'comment' | 'purchase' | 'search' | 'click';
  content_id?: string;
  content_type?: 'article' | 'video' | 'product' | 'course' | 'community_post';
  category?: string;
  tags?: string[];
  duration?: number; // 浏览时长（秒）
  timestamp: string;
  context?: {
    platform?: string;
    device?: string;
    location?: string;
    referrer?: string;
  };
}

// 用户画像接口
export interface UserProfile {
  user_id: string;
  demographics: {
    age_range?: string;
    gender?: string;
    location?: string;
    education?: string;
    income_level?: string;
  };
  parenting_info: {
    parenting_stage?: 'pregnant' | 'newborn' | 'infant' | 'toddler' | 'preschool' | 'school_age';
    children_count?: number;
    children_ages?: number[];
    parenting_style?: 'authoritative' | 'permissive' | 'authoritarian' | 'uninvolved';
    concerns?: string[];
  };
  interests: {
    categories: string[];
    topics: string[];
    brands: string[];
    price_sensitivity?: 'low' | 'medium' | 'high';
  };
  behavior_patterns: {
    active_hours: string[];
    preferred_content_types: string[];
    engagement_level: 'low' | 'medium' | 'high';
    purchase_frequency: 'rare' | 'occasional' | 'frequent';
    social_activity: 'lurker' | 'occasional' | 'active';
  };
  preferences: {
    content_length: 'short' | 'medium' | 'long';
    content_format: string[];
    notification_frequency: 'minimal' | 'moderate' | 'frequent';
    privacy_level: 'public' | 'friends' | 'private';
  };
  updated_at: string;
}

// 内容标签接口
export interface ContentTag {
  id: string;
  name: string;
  category: string;
  weight: number;
  parent_tag?: string;
  related_tags: string[];
  description?: string;
}

// 推荐结果接口
export interface RecommendationResult {
  content_id: string;
  content_type: string;
  title: string;
  description: string;
  thumbnail?: string;
  score: number;
  reason: string;
  tags: string[];
  category: string;
  author?: {
    id: string;
    name: string;
    avatar?: string;
  };
  metadata?: {
    duration?: number;
    difficulty?: string;
    age_appropriate?: string;
    price?: number;
  };
}

// 推荐参数接口
export interface RecommendationParams {
  user_id: string;
  content_types?: string[];
  categories?: string[];
  limit?: number;
  exclude_seen?: boolean;
  diversity_factor?: number; // 0-1, 多样性因子
  freshness_factor?: number; // 0-1, 新鲜度因子
  context?: {
    platform?: string;
    page_type?: string;
    time_of_day?: string;
    session_context?: any;
  };
}

// A/B测试配置接口
export interface ABTestConfig {
  test_id: string;
  name: string;
  description: string;
  variants: {
    id: string;
    name: string;
    weight: number;
    config: any;
  }[];
  target_audience?: {
    user_segments?: string[];
    demographics?: any;
    behavior_criteria?: any;
  };
  metrics: string[];
  start_date: string;
  end_date: string;
  status: 'draft' | 'active' | 'paused' | 'completed';
}

class RecommendationService {
  private baseURL = '/api/recommendation';

  /**
   * 记录用户行为
   */
  async trackUserBehavior(behavior: UserBehavior): Promise<{ success: boolean }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/behavior/track`, behavior);
      return response.data;
    } catch (error) {
      console.error('记录用户行为失败:', error);
      throw new Error('行为追踪服务暂时不可用');
    }
  }

  /**
   * 批量记录用户行为
   */
  async trackUserBehaviorBatch(behaviors: UserBehavior[]): Promise<{ success: boolean; processed: number }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/behavior/track-batch`, { behaviors });
      return response.data;
    } catch (error) {
      console.error('批量记录用户行为失败:', error);
      throw new Error('批量行为追踪服务暂时不可用');
    }
  }

  /**
   * 获取用户行为分析
   */
  async getUserBehaviorAnalysis(userId: string, timeRange?: { start: string; end: string }): Promise<{
    total_actions: number;
    action_breakdown: { [key: string]: number };
    content_preferences: {
      categories: { name: string; count: number; percentage: number }[];
      content_types: { name: string; count: number; percentage: number }[];
      tags: { name: string; count: number; weight: number }[];
    };
    engagement_patterns: {
      peak_hours: string[];
      active_days: string[];
      session_duration: number;
      bounce_rate: number;
    };
    trends: {
      period: string;
      actions: number;
      engagement_score: number;
    }[];
  }> {
    try {
      const params = timeRange ? { ...timeRange } : {};
      const response = await apiClient.get(`${this.baseURL}/behavior/analysis/${userId}`, { params });
      return response.data;
    } catch (error) {
      console.error('获取用户行为分析失败:', error);
      throw new Error('行为分析服务暂时不可用');
    }
  }

  /**
   * 获取用户画像
   */
  async getUserProfile(userId: string): Promise<UserProfile> {
    try {
      const response = await apiClient.get(`${this.baseURL}/profile/${userId}`);
      return response.data;
    } catch (error) {
      console.error('获取用户画像失败:', error);
      throw new Error('用户画像服务暂时不可用');
    }
  }

  /**
   * 更新用户画像
   */
  async updateUserProfile(userId: string, profileData: Partial<UserProfile>): Promise<UserProfile> {
    try {
      const response = await apiClient.put(`${this.baseURL}/profile/${userId}`, profileData);
      return response.data;
    } catch (error) {
      console.error('更新用户画像失败:', error);
      throw new Error('用户画像更新服务暂时不可用');
    }
  }

  /**
   * 生成用户画像（基于行为数据）
   */
  async generateUserProfile(userId: string): Promise<UserProfile> {
    try {
      const response = await apiClient.post(`${this.baseURL}/profile/generate/${userId}`);
      return response.data;
    } catch (error) {
      console.error('生成用户画像失败:', error);
      throw new Error('用户画像生成服务暂时不可用');
    }
  }

  /**
   * 获取个性化推荐
   */
  async getPersonalizedRecommendations(params: RecommendationParams): Promise<{
    recommendations: RecommendationResult[];
    total: number;
    algorithm_version: string;
    generated_at: string;
    next_refresh: string;
  }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/personalized`, params);
      return response.data;
    } catch (error) {
      console.error('获取个性化推荐失败:', error);
      throw new Error('个性化推荐服务暂时不可用');
    }
  }

  /**
   * 获取相似内容推荐
   */
  async getSimilarContentRecommendations(contentId: string, limit: number = 10): Promise<{
    recommendations: RecommendationResult[];
    similarity_scores: { content_id: string; score: number }[];
  }> {
    try {
      const response = await apiClient.get(`${this.baseURL}/similar/${contentId}`, {
        params: { limit }
      });
      return response.data;
    } catch (error) {
      console.error('获取相似内容推荐失败:', error);
      throw new Error('相似内容推荐服务暂时不可用');
    }
  }

  /**
   * 获取热门内容推荐
   */
  async getTrendingRecommendations(params: {
    category?: string;
    content_type?: string;
    time_range?: 'hour' | 'day' | 'week' | 'month';
    limit?: number;
  }): Promise<{
    recommendations: RecommendationResult[];
    trending_score: { content_id: string; score: number; trend: 'rising' | 'stable' | 'declining' }[];
  }> {
    try {
      const response = await apiClient.get(`${this.baseURL}/trending`, { params });
      return response.data;
    } catch (error) {
      console.error('获取热门内容推荐失败:', error);
      throw new Error('热门内容推荐服务暂时不可用');
    }
  }

  /**
   * 获取内容标签
   */
  async getContentTags(contentId: string): Promise<{
    tags: ContentTag[];
    auto_generated: ContentTag[];
    manual_tags: ContentTag[];
    confidence_scores: { tag_id: string; confidence: number }[];
  }> {
    try {
      const response = await apiClient.get(`${this.baseURL}/tags/content/${contentId}`);
      return response.data;
    } catch (error) {
      console.error('获取内容标签失败:', error);
      throw new Error('内容标签服务暂时不可用');
    }
  }

  /**
   * 自动生成内容标签
   */
  async generateContentTags(contentId: string, content: {
    title: string;
    description: string;
    content_body?: string;
    media_urls?: string[];
  }): Promise<{
    generated_tags: ContentTag[];
    confidence_scores: { tag_id: string; confidence: number }[];
    processing_time: number;
  }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/tags/generate/${contentId}`, content);
      return response.data;
    } catch (error) {
      console.error('生成内容标签失败:', error);
      throw new Error('内容标签生成服务暂时不可用');
    }
  }

  /**
   * 更新内容标签
   */
  async updateContentTags(contentId: string, tags: {
    add_tags?: string[];
    remove_tags?: string[];
    manual_tags?: string[];
  }): Promise<{ success: boolean; updated_tags: ContentTag[] }> {
    try {
      const response = await apiClient.put(`${this.baseURL}/tags/content/${contentId}`, tags);
      return response.data;
    } catch (error) {
      console.error('更新内容标签失败:', error);
      throw new Error('内容标签更新服务暂时不可用');
    }
  }

  /**
   * 获取标签层次结构
   */
  async getTagHierarchy(): Promise<{
    categories: {
      id: string;
      name: string;
      tags: ContentTag[];
      subcategories?: any[];
    }[];
    tag_relationships: {
      parent: string;
      children: string[];
      related: string[];
    }[];
  }> {
    try {
      const response = await apiClient.get(`${this.baseURL}/tags/hierarchy`);
      return response.data;
    } catch (error) {
      console.error('获取标签层次结构失败:', error);
      throw new Error('标签层次结构服务暂时不可用');
    }
  }

  /**
   * 搜索推荐
   */
  async getSearchRecommendations(query: string, userId?: string, filters?: {
    categories?: string[];
    content_types?: string[];
    price_range?: { min: number; max: number };
    age_range?: string;
  }): Promise<{
    recommendations: RecommendationResult[];
    search_suggestions: string[];
    related_queries: string[];
    filters_applied: any;
  }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/search`, {
        query,
        user_id: userId,
        filters
      });
      return response.data;
    } catch (error) {
      console.error('获取搜索推荐失败:', error);
      throw new Error('搜索推荐服务暂时不可用');
    }
  }

  /**
   * 记录推荐反馈
   */
  async recordRecommendationFeedback(feedback: {
    user_id: string;
    recommendation_id: string;
    content_id: string;
    action: 'click' | 'like' | 'dislike' | 'share' | 'ignore' | 'hide';
    rating?: number; // 1-5
    reason?: string;
    timestamp: string;
  }): Promise<{ success: boolean }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/feedback`, feedback);
      return response.data;
    } catch (error) {
      console.error('记录推荐反馈失败:', error);
      throw new Error('推荐反馈服务暂时不可用');
    }
  }

  /**
   * 获取推荐性能指标
   */
  async getRecommendationMetrics(params: {
    time_range?: { start: string; end: string };
    user_segment?: string;
    content_type?: string;
    algorithm_version?: string;
  }): Promise<{
    overall_metrics: {
      click_through_rate: number;
      conversion_rate: number;
      engagement_rate: number;
      diversity_score: number;
      novelty_score: number;
    };
    performance_by_category: {
      category: string;
      metrics: any;
    }[];
    user_satisfaction: {
      average_rating: number;
      feedback_distribution: { rating: number; count: number }[];
    };
    algorithm_comparison: {
      version: string;
      performance: any;
    }[];
  }> {
    try {
      const response = await apiClient.get(`${this.baseURL}/metrics`, { params });
      return response.data;
    } catch (error) {
      console.error('获取推荐性能指标失败:', error);
      throw new Error('推荐指标服务暂时不可用');
    }
  }

  /**
   * 创建A/B测试
   */
  async createABTest(testConfig: Omit<ABTestConfig, 'test_id'>): Promise<ABTestConfig> {
    try {
      const response = await apiClient.post(`${this.baseURL}/ab-test`, testConfig);
      return response.data;
    } catch (error) {
      console.error('创建A/B测试失败:', error);
      throw new Error('A/B测试服务暂时不可用');
    }
  }

  /**
   * 获取A/B测试结果
   */
  async getABTestResults(testId: string): Promise<{
    test_config: ABTestConfig;
    results: {
      variant_id: string;
      variant_name: string;
      participants: number;
      metrics: { [key: string]: number };
      statistical_significance: boolean;
      confidence_level: number;
    }[];
    winner?: string;
    recommendations: string[];
  }> {
    try {
      const response = await apiClient.get(`${this.baseURL}/ab-test/${testId}/results`);
      return response.data;
    } catch (error) {
      console.error('获取A/B测试结果失败:', error);
      throw new Error('A/B测试结果服务暂时不可用');
    }
  }

  /**
   * 获取用户分群
   */
  async getUserSegments(userId?: string): Promise<{
    segments: {
      id: string;
      name: string;
      description: string;
      criteria: any;
      user_count: number;
      characteristics: string[];
    }[];
    user_segments?: string[]; // 如果提供了userId
  }> {
    try {
      const url = userId ? `${this.baseURL}/segments/user/${userId}` : `${this.baseURL}/segments`;
      const response = await apiClient.get(url);
      return response.data;
    } catch (error) {
      console.error('获取用户分群失败:', error);
      throw new Error('用户分群服务暂时不可用');
    }
  }

  /**
   * 获取推荐算法配置
   */
  async getAlgorithmConfig(): Promise<{
    algorithms: {
      id: string;
      name: string;
      description: string;
      parameters: any;
      weight: number;
      status: 'active' | 'inactive';
    }[];
    ensemble_config: {
      combination_method: string;
      weights: { [key: string]: number };
    };
    feature_config: {
      user_features: string[];
      content_features: string[];
      context_features: string[];
    };
  }> {
    try {
      const response = await apiClient.get(`${this.baseURL}/algorithm/config`);
      return response.data;
    } catch (error) {
      console.error('获取推荐算法配置失败:', error);
      throw new Error('算法配置服务暂时不可用');
    }
  }

  /**
   * 更新推荐算法配置
   */
  async updateAlgorithmConfig(config: any): Promise<{ success: boolean; updated_config: any }> {
    try {
      const response = await apiClient.put(`${this.baseURL}/algorithm/config`, config);
      return response.data;
    } catch (error) {
      console.error('更新推荐算法配置失败:', error);
      throw new Error('算法配置更新服务暂时不可用');
    }
  }
}

// 导出服务实例
export const recommendationService = new RecommendationService();
export default RecommendationService;